package com.hydra.cron.server.quartz;

import com.alibaba.fastjson.JSONObject;
import com.hydra.cron.common.constants.C;
import com.hydra.cron.common.curator.helper.CuratorHelper;
import com.hydra.cron.common.utils.ObjectUtil;
import com.hydra.cron.server.model.CronTask;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.List;
import java.util.Random;

/**
 * hdyraCron Created by ZhengGong on 15/12/8.
 * PackageName com.hydra.cron.server
 * Description
 */
public class SimpleJob implements Job {
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        System.out.println("hello world    :   " + jobExecutionContext.getMergedJobDataMap().get("cronTask"));

        CronTask cronTask = JSONObject.parseObject((String) jobExecutionContext.getMergedJobDataMap().get("cronTask"), CronTask.class);

        try {
            boolean isRun = false;
            if (CuratorHelper.getInstance().checkExists(C.PATH.WORK_PATH)) {
                List<String> serverNameList = CuratorHelper.getChildrenNodePath(C.PATH.WORK_PATH);
                if (ObjectUtil.isEmpty(serverNameList)) {
                    return;
                }

                List<String> tokenList = null;

                for (String serverName : serverNameList) {
                    if (serverName.equals(cronTask.getServerName())) {
                        List<String> jobKeyList = CuratorHelper.getChildrenNodePath(C.PATH.WORK_PATH + "/" + cronTask.getServerName());

                        if (ObjectUtil.isNotEmpty(jobKeyList)) {
                            for (String jobKey : jobKeyList) {
                                if (jobKey.equals(cronTask.getJobKey())) {
                                    tokenList = CuratorHelper.getChildrenNodePath(C.PATH.WORK_PATH + "/" + cronTask.getServerName() + "/" + jobKey);
                                }
                            }
                        }
                    }
                }

                if (ObjectUtil.isNotEmpty(tokenList)) {

                    for (String token : tokenList) {
                        if (C.JOB_STATUS.RUN.equals(CuratorHelper.getInstance().getData(C.PATH.WORK_PATH + "/" + cronTask.getServerName() + "/" + cronTask.getJobKey() + "/" + token))) {
                            isRun = true;
                        }
                    }

                    if (isRun) {
                        return;
                    }

                    CuratorHelper.getInstance().update(C.PATH.WORK_PATH + "/" + cronTask.getServerName() + "/" + cronTask.getJobKey() + "/" + tokenList.get(new Random().nextInt(tokenList.size())), C.JOB_STATUS.RUN);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
